package com.c.ctgproject.ui.collect

import android.content.Intent
import android.view.View
import android.widget.TextView
import androidx.constraintlayout.utils.widget.ImageFilterView
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import com.bumptech.glide.Glide
import com.c.ctgproject.R
import com.c.ctgproject.adapter.ImageCommonRvAdapter
import com.c.ctgproject.adapter.PhotoShowListAdapter
import com.c.ctgproject.adapter.guang.CarImageAdapter
import com.c.ctgproject.adapter.guang.FirstCheckCountAdapter
import com.c.ctgproject.base.BaseActivityV2
import com.c.ctgproject.databinding.ActivityDestroyCarUploadImageBinding
import com.c.ctgproject.entity.guang.CarInfoEntityV2
import com.c.ctgproject.event.PositionEvent
import com.c.ctgproject.http.ApiMethods
import com.c.ctgproject.http.MyObserverHandlerLoading
import com.c.ctgproject.utils.*
import com.c.ctgproject.wiget.PhotoListShowRecyclerView
import com.c.ctgproject.wiget.common.CarInfoLayout
import com.c.ctgproject.wiget.dialog.ShowImgVideoFragment
import com.lwkandroid.imagepicker.ImagePicker
import com.lwkandroid.imagepicker.data.ImageBean
import com.lwkandroid.widget.ninegridview.NineGridBean
import org.greenrobot.eventbus.EventBus
import org.jetbrains.anko.imageResource
import org.jetbrains.anko.textColorResource
import java.io.File
import kotlin.collections.ArrayList
import kotlin.collections.HashMap

/**
 *作者:LiBW
 *创建日期: 2021/9/10
 *描述:车辆 毁型拍照 页面
 */
class DestroyCarUploadImageActivity : BaseActivityV2() {
    private val mBinding by lazy { ActivityDestroyCarUploadImageBinding.inflate(layoutInflater) }
    override fun getLayout() = mBinding.root
    private val imageShowList = ArrayList<String>()
    private val imageResultCode = 100
    private val carId by lazy { intent.getIntExtra(MyConstants.CAR_ID, -1) }
    private val mListPosition by lazy { intent.getIntExtra(MyConstants.POSITION, -1) }
    override fun event() {
        ApiMethods.apiSubscribe(ApiMethods.retrofit.carDetail(carId.handlerNull()), MyObserverHandlerLoading(this, loading) {
            MyLog.d("车辆详情回调:$it")
            val entity = getGson().fromJson(it, CarInfoEntityV2::class.java)
            if (entity.status != 1) {
                showToast("车辆编码有误")
                finish()
                return@MyObserverHandlerLoading
            }

            entity?.data?.let { data ->
                mBinding.mScrollView.visibility = View.VISIBLE
                mBinding.mContainer1.addView(CarInfoLayout(this, "制单人", data.createPersonName.noDataHandler()))
                mBinding.mContainer1.addView(CarInfoLayout(this, "收车时间", data.createTime.noDataHandler()))
                mBinding.mContainer1.addView(CarInfoLayout(this, "车辆来源", data.carSource.noDataHandler()))
                val energy = when (data.energy) {
                    1 -> "燃油车"
                    2 -> "电动车"
                    3 -> "油电混合"
                    else -> "暂无数据"
                }
                mBinding.mContainer1.addView(CarInfoLayout(this, "能源类型", energy))
                val hasBattery = when (data.hasBattery) {
                    1 -> "有"
                    0 -> "无"
                    else -> "暂无数据"
                }

                mBinding.mContainer1.addView(CarInfoLayout(this, "有无电池", hasBattery))
                mBinding.mContainer1.addView(CarInfoLayout(this, "车牌号", data.carPlate.noDataHandler()))
                mBinding.mContainer1.addView(CarInfoLayout(this, "VIN码", data.carVin.noDataHandler()))
                data.carEngine?.let {
                    mBinding.mContainer1.addView(CarInfoLayout(this, "发动机号", data.carEngine.noDataHandler()))
                }
                mBinding.mContainer1.addView(CarInfoLayout(this, "车型", data.carModel.noDataHandler()))
                val carType = when (data.carType) {
                    1 -> "社会车"
                    2 -> "试验车"
                    3 -> "外包车"
                    4 -> "五类车"
                    5 -> "农机具"
                    else -> "暂无数据"
                }
                mBinding.mContainer1.addView(CarInfoLayout(this, "车辆性质", carType))
                val statue = when (data.carStatus) {
                    1 -> "整车"
                    2 -> "车架"
                    else -> "暂无数据"
                }
                mBinding.mContainer1.addView(CarInfoLayout(this, "车辆状态", statue))
                mBinding.mContainer1.addView(CarInfoLayout(this, "车辆自编码", data.carCode.noDataHandler()))
                mBinding.mContainer1.addView(CarInfoLayout(this, "路桥费", data.toll.noDataHandler()))
                mBinding.mContainer1.addView(CarInfoLayout(this, "预录入备注", data.preRemark.noDataHandler()))


                val entrance = when (data.entrance) {
                    1 -> {
                        "已完成"
                    }
                    0 -> {
                        "未完成"
                    }
                    2 -> {
                        "驳回"
                    }
                    else -> "暂无数据"
                }
                mBinding.mContainer2.addView(CarInfoLayout(this, "登记入库", entrance))
                mBinding.mContainer2.addView(CarInfoLayout(this, "过磅", data.pound.finishHandler()))
                mBinding.mContainer2.addView(CarInfoLayout(this, "初检", data.carCheck.finishHandler()))
                mBinding.mContainer2.addView(CarInfoLayout(this, "排油水", data.oilWaterDrainage.finishHandler()))
                mBinding.mContainer2.addView(CarInfoLayout(this, "拆电池", data.batteryDisassemble.finishHandler()))
                mBinding.mContainer2.addView(CarInfoLayout(this, "预处理", data.pretreatment.finishHandler()))
                val dismantle = when (data.dismantle) {
                    0 -> "未拆解"
                    1 -> "拆解中"
                    2 -> "已完成"
                    else -> "暂无数据"

                }

                mBinding.mContainer2.addView(CarInfoLayout(this, "拆解", dismantle))

                val dismantleType = when (data.dismantleType) {
                    1 -> "毁型"
                    2 -> "拆配件"
                    else -> "暂无数据"
                }
                mBinding.mContainer2.addView(CarInfoLayout(this, "拆解方式", dismantleType))

                data.carPartsList?.let {
                    mBinding.mCountRV.adapter = FirstCheckCountAdapter(this, it)
                    mBinding.mCountRV.layoutManager = LinearLayoutManager(this)

                }
                //车辆图片
                data.carPictures?.let { list ->
                    if (list.isNotEmpty()) {
                        mBinding.mContainer6.visibility = View.VISIBLE
                        mBinding.mCarImageRV.adapter = CarImageAdapter(this, list)
                        mBinding.mCarImageRV.layoutManager = LinearLayoutManager(this)
                    }
                }
                data?.batteryInfo?.let {
                    mBinding.mContainer7.addView(CarInfoLayout(this, "电池名称", it.batteryName.noDataHandler()))
                    mBinding.mContainer7.addView(CarInfoLayout(this, "电池编码", it.batteryCode.noDataHandler()))
                    mBinding.mContainer7.addView(CarInfoLayout(this, "电池自编码", it.batterySelfCode.noDataHandler()))
                    mBinding.mContainer7.addView(CarInfoLayout(this, "电池数量", it.count.noDataHandler()))
                    mBinding.mContainer7.addView(CarInfoLayout(this, "模组个数", it.moduleCount.noDataHandler()))
                    mBinding.mContainer7.addView(CarInfoLayout(this, "重量KG", it.weight.noDataHandler()))
                    mBinding.mContainer7.addView(CarInfoLayout(this, "容量Ah", it.capacityAh.noDataHandler()))
                    mBinding.mContainer7.addView(CarInfoLayout(this, "电压V", it.voltage.noDataHandler()))
                    mBinding.mContainer7.addView(CarInfoLayout(this, "容量Kwh", it.capacityKwh.noDataHandler()))
                    mBinding.mContainer7.addView(CarInfoLayout(this, "备注", it.remark.noDataHandler()))
                }
                //电池图片列表
                data?.batteryInfo?.batteryPictures?.let {

                    val adapter = ImageCommonRvAdapter(this, it)
                    mBinding.mContainer7.addView(CarInfoLayout(this, "电池拆解", ""))
                    mBinding.mBatteryImageRV.visibility = View.VISIBLE
                    mBinding.mBatteryImageRV.adapter = adapter
                    mBinding.mBatteryImageRV.layoutManager = GridLayoutManager(this, 3, GridLayoutManager.VERTICAL, false)
                }
//                mBinding.mContainer3.addView(CarInfoLayout(this, "发动机", data.engine.noDataHandler()))
//                mBinding.mContainer3.addView(CarInfoLayout(this, "变速箱", data.transmissionCase.noDataHandler()))
//                mBinding.mContainer3.addView(CarInfoLayout(this, "三元催化", data.ternaryCatalysis.noDataHandler()))
//                mBinding.mContainer3.addView(CarInfoLayout(this, "蓄电池", data.battery.noDataHandler()))
//                mBinding.mContainer3.addView(CarInfoLayout(this, "动力电池", data.powerBattery.noDataHandler()))
//                mBinding.mContainer3.addView(CarInfoLayout(this, "耦合电机", data.couplingMotor.noDataHandler()))


                mBinding.mContainer4.addView(CarInfoLayout(this, "过磅人", data.poundPersonName.noDataHandler()))
                mBinding.mContainer4.addView(CarInfoLayout(this, "磅单号", data.poundNo.noDataHandler()))
                mBinding.mContainer4.addView(CarInfoLayout(this, "过磅重量KG", data.poundWeight.noDataHandler()))
                mBinding.mContainer4.addView(CarInfoLayout(this, "采购单号", data.purchasePoundNo.noDataHandler()))
                mBinding.mContainer4.addView(CarInfoLayout(this, "采购重量KG", data.purchaseWeight.noDataHandler()))
                mBinding.mContainer4.addView(CarInfoLayout(this, "过磅时间", data.poundTime.noDataHandler()))
                val image = data.poundPicture.handlerNull()
                if (image.isNotEmpty()) {
                    mBinding.mImageViewTV.visibility = View.VISIBLE
                    mBinding.mImageView.visibility = View.VISIBLE
                    Glide.with(this).load(image).error(R.mipmap.app_icon).into(mBinding.mImageView)
                    mBinding.mImageView.setOnClickListener {
                        ShowImgVideoFragment(image).show(supportFragmentManager, "")
                    }
                }
                val imageUrl = data.poundPicture.handlerNull()
                mBinding.mContainer5.addView(CarInfoLayout(this, "物流单号", data.logisticsNo.noDataHandler()))
                mBinding.mContainer5.addView(CarInfoLayout(this, "物流公司", data.logisticsCompany.noDataHandler()))
                mBinding.mContainer5.addView(CarInfoLayout(this, "发货地址", data.sendAddress.noDataHandler()))
                mBinding.mContainer5.addView(CarInfoLayout(this, "收货地址", data.receiveAddress.noDataHandler()))
                mBinding.mContainer5.addView(CarInfoLayout(this, "送货司机", data.driverName.noDataHandler()))
                mBinding.mContainer5.addView(CarInfoLayout(this, "物流车牌", data.logisticsPlate.noDataHandler()))
                mBinding.mContainer5.addView(CarInfoLayout(this, "物流费用", data.logisticsCost.noDataHandler()))
                //处理完成状态
//                handlerStatue(data.pound == 1, mBinding.mWeighIV, mBinding.mWeighTV, mBinding.mWeighLine)
//                handlerStatue(data.carCheck == 1, mBinding.mCheckIV, mBinding.mCheckTV, mBinding.mCheckLine)
//                handlerStatue(data.pretreatment == 1, mBinding.mPreIV, mBinding.mPreTV, mBinding.mPreLine)
//                handlerStatue(data.entrance == 1, mBinding.mInIV, mBinding.mInTV, null)
//                //拆解完成是2
//                handlerStatue(data.dismantle == 2, mBinding.mHandlerIV, mBinding.mHandlerTV, mBinding.mHandlerLine)
            }
        })

        mBinding.mPhotoNGV.init(this, imageShowList, 6, imageResultCode)
        mBinding.mPhotoList.setPhotoListShowCallBack(object : PhotoListShowRecyclerView.PhotoListShowCallBack {
            override fun selectedPhoto(urls: List<String>): Boolean {
                var index = 0
                val fileList = ArrayList<File>()
                urls.forEach {
                    index++
                    val file = File(it)
                    //图片压缩
//                    val newFile: File = CompressHelper.getDefault(this).compressToFile(file)
//                    val newFile=ImageUtil.imageWaterMark(this,file,index)
                    val newFile: File = WaterRemark.handlerWaterRemark2File(baseContext, file, index.toString())
                    fileList.add(newFile)
                }
                loading.dismiss()
                upDataFile(fileList) {
                    val dataList = ArrayList<String>()
                    it?.forEach { b ->
                        dataList.add(b.fileUrl.handlerNull())
                    }
                    mBinding.mPhotoList.addPhotos(dataList)
                }
                return false
            }

            override fun deletePhoto(url: String): Boolean {
                return true
            }

        })
    }

    //    private fun handlerStatue(finish: Boolean, icon: ImageFilterView, text: TextView, line: View? = null) {
//        if (finish) {
//            icon.imageResource = R.mipmap.icon_finish
////            line?.backgroundResource = R.color.colorAccent
//            text.textColorResource = R.color.colorAccent
//        } else {
//            icon.imageResource = R.mipmap.icon_unstart
////            line?.backgroundResource = R.color.gray_text
//            text.textColorResource = R.color.gray_text
//        }
//    }
    override fun click() {
        //返回
        mBinding.mBackIv.setOnClickListener {
            finish()
        }
//        mBinding.mConfirmBTN.setOnClickListener {
//            if (imageShowList.isEmpty()) {
//                showToast("请至少选择一张照片上传")
//            } else {
//                val fileList = ArrayList<File>()
//                var index=0
//                loading.show()
//                imageShowList.forEach {
//                    index++
//                    val file = File(it)
//                    //图片压缩
////                    val newFile: File = CompressHelper.getDefault(this).compressToFile(file)
////                    val newFile=ImageUtil.imageWaterMark(this,file,index)
//                    val newFile: File = WaterRemark.handlerWaterRemark2File(this, file, index.toString())
//                    fileList.add(newFile)
//                }
//                loading.dismiss()
//                upDataFile(fileList) {
//                    val dataList = ArrayList<String>()
//                    it?.forEach { b ->
//                        dataList.add(b.fileUrl.handlerNull())
//                    }
//                    val map=HashMap<String,Any>()
//                    map["carId"]=carId
//                    map["picUrls"]=dataList
//
//                    ApiMethods.apiSubscribe(ApiMethods.retrofit.uploadDestroyImage(handlerBody(map)), MyObserverHandlerLoading(this, loading) {
//                        showToast("提交成功")
//                        EventBus.getDefault().post(PositionEvent(mListPosition))
//                        finish()
//                    })
//                }
//            }
//        }
        mBinding.mConfirmBTN.setOnClickListener {
            val images = mBinding.mPhotoList.getPhotos()
            if (images.isEmpty()) {
                showToast("请至少选择一张照片上传")
            } else {
                val map = HashMap<String, Any>()
                map["carId"] = carId
                map["picUrls"] = images

                ApiMethods.apiSubscribe(ApiMethods.retrofit.uploadDestroyImage(handlerBody(map)), MyObserverHandlerLoading(this, loading) {
                    showToast("提交成功")
                    EventBus.getDefault().post(PositionEvent(mListPosition))
                    finish()
                })

            }
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        data?.let {
            when (requestCode) {
                //图片回调
                imageResultCode -> {
                    val list: List<ImageBean>? = data.getParcelableArrayListExtra(ImagePicker.INTENT_RESULT_DATA)
                    val resultList: MutableList<NineGridBean> = ArrayList()
                    list?.forEach { imageBean ->
                        val nineGirdData = NineGridBean(imageBean.imagePath)
                        imageShowList.add(imageBean.imagePath)
                        resultList.add(nineGirdData)
                    }
                    mBinding.mPhotoNGV.addDataList(resultList)
                }
                else -> {

                }
            }
        }
    }
}